<!DOCTYPE html>
<html>
<head>
    <title>Circuit Diagram 4.21.1</title>
    <style>
        body {
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100vh;
            margin: 0;
        }
        canvas {
            border: 1px solid #ccc;
        }
    </style>
</head>
<body>
    <canvas id="circuitCanvas" width="450" height="480"></canvas>
    <script>
        const canvas = document.getElementById('circuitCanvas');
        const ctx = canvas.getContext('2d');

        // Grid parameters
        const x_start = 100;
        const y_start = 100;
        const s = 60; // size of one square
        const n = 4;  // number of squares per side
        const grid_size = n * s;

        // Draw the grid
        ctx.beginPath();
        ctx.lineWidth = 2;
        ctx.strokeStyle = 'black';

        // Horizontal lines
        for (let i = 0; i <= n; i++) {
            ctx.moveTo(x_start, y_start + i * s);
            ctx.lineTo(x_start + grid_size, y_start + i * s);
        }

        // Vertical lines
        for (let j = 0; j <= n; j++) {
            ctx.moveTo(x_start + j * s, y_start);
            ctx.lineTo(x_start + j * s, y_start + grid_size);
        }
        ctx.stroke();

        // Draw labels
        ctx.fillStyle = 'black';
        
        // Main labels A and B
        ctx.font = 'italic 24px Times New Roman';
        // Label A (bottom-left)
        ctx.fillText('A', x_start - 25, y_start + grid_size + 10);
        
        // Label R and B (top-right)
        ctx.fillText('R', x_start + grid_size - 30, y_start - 10);
        ctx.fillText('B', x_start + grid_size + 5, y_start - 10);

        // Subscript labels M1 and M2
        // Label M1
        ctx.fillText('M', x_start - 35, y_start + (n - 1) * s + 8);
        ctx.font = 'italic 16px Times New Roman';
        ctx.fillText('1', x_start - 18, y_start + (n - 1) * s + 13);
        
        // Label M2
        ctx.font = 'italic 24px Times New Roman';
        ctx.fillText('M', x_start + s - 10, y_start + grid_size + 28);
        ctx.font = 'italic 16px Times New Roman';
        ctx.fillText('2', x_start + s + 7, y_start + grid_size + 33);
        
        // Draw the caption
        ctx.font = '24px "SimSun", "Songti SC", serif';
        ctx.fillText('电图 4.21.1', 155, 420);

    </script>
</body>
</html>